import React, {memo, useEffect, useState} from 'react';

import "./index.css";
import {useDispatch, useSelector} from "react-redux";
import request from "../../services/request";
import {message, Modal, Upload} from "antd";
import {BASE_URL} from "../../services/config";
import {calCqMean, deepClone, getContextPath, modifyData} from "../../common/utils";
import {saveData} from "../../pages/main/store/actionCreators";
import {LOAD_ANALYSIS, LOAD_PLATE, LOAD_PROTOCOL} from "../../common/loadType";
import {saveTargetSelectedArr} from "../../pages/main/analysis/components/quantification/store/actionCreators";
import {saveAnalysisShowLineArr, saveEndogenousControlTarget, saveGroup, saveReferenceSample} from "../../pages/main/plate/store/actionCreators";
import {LINE_OBJ} from "../../pages/main/plate/config";
import {saveCurrentTempData, saveMeltData, savePcrData} from "../../pages/main/run/store/actionCreators";
import {saveRunTargetSelectedArr} from "../../pages/main/run/components/realtimeCurve/store/actionCreators";
import {useChangeCoordinate, useSaveEndPointSetting} from "../../common/myHooks";
import {saveChartOption, saveExperimentSetting, saveTableData} from "../../pages/main/analysis/components/geneExpression/store/actionCreators";
import {saveIsLoad} from "../../pages/main/calculation/components/quantification/store/actionCreators";
import {saveDegree} from "../../pages/main/analysis/components/allelicDiscrimination/store/actionCreators";

export default memo(function Header(props) {
  const {
    name,
    isSave,
    isExport,
    isLoad,
    isMore,
    imgPosition,
    isAnalysis,
    iconStyle,
    analysisAction,
    saveAction,
    isRefresh,
    moreAction,
    refreshAction,
    loadConfig,
    loadType,
    isSaveWordAndPdf,
    setShowExportAside
  } = props;
  const dispatch = useDispatch();
  const {data, exportObj, exportObjCn, isCN, runStart, isLoadDone} = useSelector(state => ({
    data: state.dataReducer.data,
    exportObj: state.exportReducer.exportObj,
    exportObjCn: state.exportReducer.exportObjCn,
    isCN: state.languageReducer.isCN,
    runStart: state.runReducer.runStart,
    isLoadDone: state.calculationReducer.isLoad
  }));
  const [url, setUrl] = useState("");
  const [visible, setVisible] = useState(false);
  const [docx, setDocx] = useState(true);
  const changeCoordinate = useChangeCoordinate();
  const saveEndPointSetting = useSaveEndPointSetting();
  let cloneData = {};
  const config = {
    name: 'file',
    showUploadList: false,
    action: `${BASE_URL}/uploadAction/upload`,
    headers: {
      authorization: 'authorization-text'
    },
    accept: ".cqa",
    onChange(info) {
      if (info.file.status === 'done') {
        if (runStart) {
          return message.warn("Experiment is starting.");
        }
        let loadData = JSON.parse(info.file.response.data); //  加载文件后返回的数据
        console.log(loadData);
        loadData.experimentName = info.file.name.split(".")[0];
        dispatch(saveIsLoad(true));
        switch (loadType) {
          case LOAD_PROTOCOL:
            dispatch(saveData({...data, hotLidMode: loadData.hotLidMode, protocol: {...data.protocol, stages: loadData.protocol.stages}}));
            break;
          case LOAD_PLATE:
            cloneData = deepClone(data, cloneData);
            cloneData.plateSetting = loadData.plateSetting;
            cloneData.targets = loadData.targets;
            cloneData.wells = loadData.wells;
            cloneData.wells.forEach(item => {
              item.lines = [{...LINE_OBJ}, {...LINE_OBJ}, {...LINE_OBJ}, {...LINE_OBJ}, {...LINE_OBJ}, {...LINE_OBJ}];
              item.meltData = [];
              item.meltPeak = [];
            });
            dispatch(saveData(cloneData));
            break;
          case LOAD_ANALYSIS:
            changeCoordinate(loadData);
            saveEndPointSetting(loadData);
            let cloneCurrentTempData = [];
            loadData.lidTemperature.forEach((item, index) => {
              cloneCurrentTempData.push({
                timestamp: item.time,
                sample: loadData.sampleTemperature[index].temperature,
                lid: item.temperature
              });
            });
            dispatch(saveDegree([]));
            dispatch(saveCurrentTempData(cloneCurrentTempData));
            dispatch(savePcrData(loadData.pcrDataOrigin));
            dispatch(saveMeltData(loadData.meltDataOrigin));
            let dataAfterModified = modifyData(loadData);  //  处理后的数据
            console.log(dataAfterModified);
            dispatch(saveTargetSelectedArr([...new Set(dataAfterModified.targetSelectedArr)]));
            dispatch(saveRunTargetSelectedArr([...new Set(dataAfterModified.targetSelectedArr)]));
            dispatch(saveAnalysisShowLineArr(dataAfterModified.analysisShowLineArr));
            dispatch(saveData(dataAfterModified.loadData));
            dispatch(saveEndogenousControlTarget(dataAfterModified.endogenousControlTarget));
            dispatch(saveReferenceSample(""));
            dispatch(saveTableData([]));
            dispatch(saveChartOption({}));
            dispatch(saveExperimentSetting(dataAfterModified.experimentSetting));
            let groupWellList = loadData.wells.filter(well => well.groupUuid !== '' && well.groupColor !== '');
            let arr = [], obj = {};
            groupWellList.forEach(item => {
              if (obj.hasOwnProperty(item.groupName)) {

              } else {
                obj[item.groupName] = item.groupName;
                arr.push({
                  uuid: item.groupUuid,
                  opt: false,
                  name: item.groupName,
                  color: item.groupColor,
                  comments: ""
                });
              }
            });
            dispatch(saveGroup(arr));
        }
        isCN
          ? message.success(`${info.file.name} 加载成功`)
          : message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        isCN
          ? message.success(`${info.file.name} 加载失败`)
          : message.error(`${info.file.name} file upload failed.`);
      }
    }
  };
  useEffect(() => {
    if (!url) {
      return;
    }
    let iframe = document.createElement("iframe");
    iframe.src = url;
    iframe.style.display = "none";
    document.body.appendChild(iframe);
    setTimeout(() => iframe.remove(), 1000);
  }, [url]);

  //  保存cqa文件
  function saveSelfAction() {
    console.log(data);
    if (runStart) {
      return message.warn("Experiment is starting.");
    }
    setUrl("");
    request({
      url: 'downloadAction/downloadAll',
      data: {
        experimentName: data.experimentName,
        userName: data.userName,
        data: JSON.stringify({...data, connectPort: ""})
      },
      method: 'post'
    }).then(() => {
      setUrl(getContextPath() + "/downloadAction/downloadAllUrl");
    }).catch(err => message.error(err));
  }

  function showModal() {
    setVisible(true);
  }

  function handleOk() {
    setVisible(false);
    let cloneExportObj = {};
    cloneExportObj = deepClone(isCN ? exportObjCn : exportObj, cloneExportObj);
    // cloneExportObj = deepClone(exportObj, cloneExportObj);
    // if(isCN){
    //   cloneExportObj.language="Chinese"
    // }
    docx ? cloneExportObj.type = "docx" : cloneExportObj.type = "pdf";
    message.info(isCN ? "请稍等....." : "Please wait a moment");
    console.log(cloneExportObj);
    setUrl("");
    request({
      url: 'reportAction/generate',
      data: cloneExportObj,
      method: 'post'
    }).then(() => {
      setUrl(getContextPath() + "/reportAction/generateUrl");
    }).catch(err => message.error(err));
  }

  function handleCancel() {
    setVisible(false);
  }

  return (
    <div>
      <header className="mainHeader">
        <div style={{"backgroundPositionY": imgPosition}} className={iconStyle}/>
        <div>{name}</div>
        {
          isMore
            ? <div className="mainHeaderMoreExperiment"
                   onClick={moreAction}
            />
            : null
        }
        {
          isExport
            ? <div className="mainHeaderExport"
                   onClick={() => setShowExportAside(true)}
            >
              <div style={{margin: "2px 10px"}}/>
              <div>{isCN ? "导出" : "EXPORT"}</div>
            </div>
            : null
        }
        {
          isSave ?
            <div className="mainHeaderSave"
                 onClick={isSaveWordAndPdf ? showModal : saveAction || saveSelfAction}
            >
              <div/>
              <div>{isCN ? "保存" : "SAVE"}</div>
            </div>
            : null
        }
        {
          isLoad ?
            <div className="mainHeaderLoad">
              {
                loadConfig
                  ? <Upload {...loadConfig}>
                    <div/>
                  </Upload>
                  : <Upload {...config}>
                    <div/>
                  </Upload>
              }
              {
                loadConfig
                  ? <Upload {...loadConfig}>
                    <div style={{position: "sticky", top: 0, paddingBottom: 4}}>{isCN ? "加载" : "LOAD"}</div>
                  </Upload>
                  : <Upload {...config}>
                    <div style={{position: "sticky", top: 0, paddingBottom: 4}}>{isCN ? "加载" : "LOAD"}</div>
                  </Upload>
              }
            </div>
            : null
        }
        {
          isAnalysis ?
            <div className="mainHeaderRefresh" onClick={analysisAction}>
              <div>{isCN ? "重分析" : "REANALYSE"}</div>
            </div> : null
        }
        {
          isRefresh ?
            <div className="mainHeaderRefresh" onClick={refreshAction}>
              <div>{isCN ? "更新" : "REFRESH"}</div>
            </div> : null
        }
      </header>
      <hr className="mainHeaderLine"/>
      <Modal
        title="Which file do you want to download?"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        wrapClassName="exportModal"
      >
        <p onClick={() => setDocx(true)}
           style={docx ? {backgroundColor: "#213040", color: "#fff"} : null}
        >
          Word(.docx)
        </p>
        <p onClick={() => setDocx(false)}
           style={docx ? null : {backgroundColor: "#213040", color: "#fff"}}
        >
          Pdf(.pdf)
        </p>
      </Modal>
    </div>
  );
});
